package com.mirror.tk.api.controller.user;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mirror.tk.api.common.Constant;
import com.mirror.tk.api.common.support.JwtFace;
import com.mirror.tk.api.common.support.JwtUser;
import com.mirror.tk.api.controller.CommonController;
import com.mirror.tk.api.utils.PwdUtil;
import com.mirror.tk.core.log.annotation.Log;
import com.mirror.tk.core.module.user.domain.User;
import com.mirror.tk.core.module.user.service.UserService;
import com.mirror.tk.framework.common.web.support.JsonEntityResult;
import com.mirror.tk.framework.common.web.support.JsonResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "登陆接口", description = "提供登陆相关操作")
@RestController
public class LoginController extends CommonController {

	@Resource
	private UserService userService;
	
	@ApiOperation(value = "登陆", notes = "通过电话号码登陆")
	@Log(module="User", moduleName="用户", action="login", actionName="通过电话号码登陆", tag="api")
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public JsonEntityResult<JwtUser> login(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "电话", required = true)@RequestParam(value = "phone", required = true)String phone,
			@ApiParam(value = "密码", required = true)@RequestParam(value = "password", required = true)String password){
		JsonEntityResult<JwtUser> result = new JsonEntityResult<JwtUser>();
		User user = userService.getUserByPhone(phone);
		if(null != user && PwdUtil.validatePassword(user, password)){
			JwtUser jwtUser = JwtUser.bulider(user);
			result.appendData("Authorization", "Bearer " + JwtFace.setJwtUser(jwtUser));
			result.setEntity(jwtUser);
			result.setSuccess(true);
			result.setCode(Constant.Global.SUCCESS);
			result.setMessage(Constant.UserMassage.USER_LOGIN_SUCCESS);
			return result;
		}
		result.setCode(Constant.Global.FAIL);
		result.setMessage(Constant.UserMassage.USER_LOGIN_FAIL);
		return result;
	}
	
	@ApiOperation(value = "退出登录", notes = "退出登录")
	@Log(module="User", moduleName="用户", action="logout", actionName="退出登录", tag="api")
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public JsonResult logout(HttpServletRequest request){
		JsonResult result = new JsonResult(JwtFace.logout(request));
		return result;
	}
	
}
